import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from pymongo import MongoClient
from config.config import Config
import pycountry

class DataFetcher:
    def __init__(self):
        self.client = MongoClient(Config.MONGODB_URI)
        self.db = self.client[Config.DB_NAME]
    
    def get_all_countries(self):
        countries = []
        for country in pycountry.countries:
            countries.append({
                'name': country.name,
                'code': country.alpha_2,
                'official_name': getattr(country, 'official_name', country.name)
            })
        countries.sort(key=lambda x: x['name'])
        return countries
    
    def get_collection_list(self):
        """Get collection list from collection_info"""
        try:
            # 优先从 collection_info 集合获取
            collections = list(self.db.collection_info.find({}, {
                'name': 1, 
                'display_name': 1, 
                'description': 1,
                'color': 1,                
                '_id': 0
            }).sort('name', 1))
            
            if collections:
                return collections
            
            # 如果 collection_info 为空，回退到原有逻辑
            collections = list(self.db.collections.find({}, {'name': 1, 'display_name': 1, '_id': 0}))
            document_collections = self.db.documents.distinct('collection')
            
            collection_set = set()
            collection_list = []
            
            for coll in collections:
                if coll['name'] not in collection_set:
                    collection_set.add(coll['name'])
                    collection_list.append({
                        'name': coll['name'],
                        'display_name': coll.get('display_name', coll['name'])
                    })
            
            for coll_name in document_collections:
                if coll_name and coll_name not in collection_set:
                    collection_set.add(coll_name)
                    collection_list.append({
                        'name': coll_name,
                        'display_name': coll_name
                    })
            
            collection_list.sort(key=lambda x: x['name'])
            return collection_list
            
        except Exception as e:
            print(f"Error getting collection list: {e}")
            return []
    
    def get_tag_list(self, search_term=None):
        all_tags = []
        documents = self.db.documents.find({'tags': {'$exists': True}}, {'tags': 1})
        
        for doc in documents:
            if 'tags' in doc and isinstance(doc['tags'], list):
                all_tags.extend(doc['tags'])
        
        unique_tags = list(set(all_tags))
        
        if search_term:
            search_lower = search_term.lower()
            unique_tags = [tag for tag in unique_tags if search_lower in tag.lower()]
        
        unique_tags.sort()
        return unique_tags
    
    def add_tag_to_list(self, tag):
        if not tag:
            return False
        
        if 'tags' not in self.db.list_collection_names():
            self.db.create_collection('tags')
        
        existing = self.db.tags.find_one({'name': tag})
        if not existing:
            self.db.tags.insert_one({
                'name': tag,
                'usage_count': 1
            })
        else:
            self.db.tags.update_one(
                {'name': tag},
                {'$inc': {'usage_count': 1}}
            )
        
        return True
    
    def search_similar_tags(self, query, limit=10):
        if not query:
            return self.get_tag_list()[:limit]
        
        all_tags = self.get_tag_list()
        query_lower = query.lower()
        
        starts_with = [tag for tag in all_tags if tag.lower().startswith(query_lower)]
        contains = [tag for tag in all_tags if query_lower in tag.lower() and not tag.lower().startswith(query_lower)]
        
        results = starts_with + contains
        return results[:limit]
    
    def close(self):
        if self.client:
            self.client.close()